<template>
  <div class="record-container">
    <!-- 原有内容保持不变 -->
    <el-tabs v-model="activeTab" @tab-click="handleTabChange" class="record-tabs">
      <el-tab-pane label="渠道总表" name="0"></el-tab-pane>
      <!-- <el-tab-pane label="渠道客户1" name="1"></el-tab-pane>
      <el-tab-pane label="渠道维护" name="2"></el-tab-pane>
      <el-tab-pane label="我的渠道" name="3"></el-tab-pane> -->
    </el-tabs>

    <el-card class="filter-card">
      <el-form :inline="true" :model="queryParams" class="filter-form">
        <el-form-item v-if="activeTab === '0'">
          <el-form-item label="渠道名称">
            <el-input
              v-model="queryParams.channelName"
              placeholder="请输入渠道名称"
              clearable
              style="width: 220px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
        <el-form-item v-if="activeTab !== '2'">
          <el-button type="primary" icon="Plus" @click="handleAddChannel"
            >新增渠道</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="list-card" style="margin-top: 18px">
      <el-table v-loading="loading" :data="companyList" style="width: 100%" border>
        <template v-for="field in fieldConfig[activeTab]" :key="field.prop">
          <!-- 普通字段 -->
          <el-table-column
            v-if="field.prop !== 'channelLevel' && field.prop !== 'category'"
            :prop="field.prop"
            :label="field.label"
            min-width="120"
            show-overflow-tooltip
          />

          <!-- 渠道级别特殊处理 -->
          <el-table-column
            v-else-if="field.prop === 'channelLevel'"
            :prop="field.prop"
            :label="field.label"
            min-width="120"
            show-overflow-tooltip
          >
            <template #default="scope">
              <el-tag
                :class="getChannelLevelTagClass(scope.row.channelLevel)"
                disable-transitions
              >
                {{ scope.row.channelLevel }}
              </el-tag>
            </template>
          </el-table-column>

          <!-- 分类特殊处理 -->
          <el-table-column
            v-else-if="field.prop === 'category'"
            :prop="field.prop"
            :label="field.label"
            min-width="120"
            show-overflow-tooltip
          >
            <template #default="scope">
              <el-tag
                :class="getCategoryTagClass(scope.row.category)"
                disable-transitions
              >
                {{ scope.row.category }}
              </el-tag>
            </template>
          </el-table-column>
        </template>

        <el-table-column
          v-if="activeTab === '0' || activeTab === '3'"
          label="操作"
          min-width="120"
          fixed="right"
        >
          <template #default="{ row }">
            <el-button type="primary" link @click="viewCompanyProfile(row.channelId)">
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 新增渠道弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      title="新建渠道"
      height="88%"
      width="600px"
      :before-close="handleClose"
    >
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="150px">
        <!-- 渠道提报人员 -->
        <el-form-item label="渠道提报人员">
          <el-input v-model="formData.tname" disabled />
        </el-form-item>

        <!-- 渠道级别 -->
        <el-form-item label="渠道级别" prop="channelLevel">
          <el-select v-model="formData.channelLevel" placeholder="请选择">
            <el-option label="公司级" value="公司级" />
            <el-option label="项目部门级" value="项目部门级" />
            <el-option label="个人级" value="个人级" />
          </el-select>
        </el-form-item>

        <!-- 渠道归属部门 -->
        <el-form-item label="渠道归属部门">
          <el-select v-model="formData.attribution" placeholder="请选择">
            <el-option
              v-for="(dept, index) in departmentList"
              :key="index"
              :label="dept"
              :value="dept"
            />
          </el-select>
        </el-form-item>

        <!-- 渠道分类 -->
        <el-form-item label="渠道分类" prop="category">
          <el-select v-model="formData.category" placeholder="请选择">
            <el-option label="政府部门" value="政府部门" />
            <el-option label="商会协会" value="商会协会" />
            <el-option label="会所律所" value="会所律所" />
            <el-option label="中介服务" value="中介服务" />
            <el-option label="合作企业" value="合作企业" />
            <el-option label="财税公司" value="财税公司" />
          </el-select>
        </el-form-item>

        <!-- 是否签约 -->
        <el-form-item label="是否签约" prop="isSigned">
          <el-select v-model="formData.isSigned" placeholder="请选择">
            <el-option label="是" value="是" />
            <el-option label="否" value="否" />
          </el-select>
        </el-form-item>

        <!-- 渠道名称 -->
        <el-form-item label="渠道名称" prop="channelName">
          <el-input v-model="formData.channelName" placeholder="请输入渠道名称" />
        </el-form-item>

        <!-- 渠道维护人员 -->
        <el-form-item label="渠道维护人员">
          <el-input v-model="formData.maintenanceStaff" />
        </el-form-item>

        <!-- 渠道联系人 -->
        <el-form-item label="渠道联系人" prop="contactPerson">
          <el-input v-model="formData.contactPerson" placeholder="请输入联系人姓名" />
        </el-form-item>

        <!-- 手机号码 -->
        <el-form-item label="手机号码" prop="contactInfo">
          <el-input v-model="formData.contactInfo" placeholder="请输入手机号码" />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit">添加</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑渠道弹窗 -->
    <!-- 编辑渠道弹窗 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑渠道"
      width="600px"
      :before-close="handleCloseEdit"
    >
      <el-form ref="editFormRef" :model="editFormData" :rules="rules" label-width="150px">
        <!-- 渠道ID（隐藏） -->
        <el-form-item label="渠道ID" prop="id" style="display: none">
          <el-input v-model="editFormData.id" />
        </el-form-item>

        <!-- 渠道提报人员 -->
        <el-form-item label="渠道提报人员">
          <el-input v-model="editFormData.tname" disabled />
        </el-form-item>

        <!-- 渠道级别 -->
        <el-form-item label="渠道级别" prop="channelLevel">
          <el-select v-model="editFormData.channelLevel" placeholder="请选择">
            <el-option label="公司级" value="公司级" />
            <el-option label="项目部门级" value="项目部门级" />
            <el-option label="个人级" value="个人级" />
          </el-select>
        </el-form-item>

        <!-- 渠道归属部门 -->
        <el-form-item label="渠道归属部门">
          <el-select v-model="editFormData.attribution" placeholder="请选择">
            <el-option
              v-for="(dept, index) in departmentList"
              :key="index"
              :label="dept"
              :value="dept"
            />
          </el-select>
        </el-form-item>

        <!-- 渠道分类 -->
        <el-form-item label="渠道分类" prop="category">
          <el-select v-model="editFormData.category" placeholder="请选择">
            <el-option label="政府部门" value="政府部门" />
            <el-option label="商会协会" value="商会协会" />
            <el-option label="会所律所" value="会所律所" />
            <el-option label="中介服务" value="中介服务" />
            <el-option label="合作企业" value="合作企业" />
            <el-option label="财税公司" value="财税公司" />
          </el-select>
        </el-form-item>

        <!-- 是否签约 -->
        <el-form-item label="是否签约" prop="isSigned">
          <el-select v-model="editFormData.isSigned" placeholder="请选择">
            <el-option label="是" value="是" />
            <el-option label="否" value="否" />
          </el-select>
        </el-form-item>

        <!-- 渠道名称 -->
        <el-form-item label="渠道名称" prop="channelName">
          <el-input v-model="editFormData.channelName" placeholder="请输入渠道名称" />
        </el-form-item>

        <!-- 渠道维护人员 -->
        <el-form-item label="渠道维护人员">
          <el-input v-model="editFormData.maintenanceStaff" />
        </el-form-item>

        <!-- 渠道联系人 -->
        <el-form-item label="渠道联系人" prop="contactPerson">
          <el-input v-model="editFormData.contactPerson" placeholder="请输入联系人姓名" />
        </el-form-item>

        <!-- 手机号码 -->
        <el-form-item label="手机号码" prop="contactInfo">
          <el-input v-model="editFormData.contactInfo" placeholder="请输入手机号码" />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCloseEdit">取消</el-button>
          <el-button type="primary" @click="handleEditSubmit">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
const { proxy } = getCurrentInstance();

import {
  getChannelMasterTableListpage,
  getChannelCustomtpage,
  getChannelMaintainpage,
  getMyChannelpage,
  addChannel,
} from "@/api/AttractInvestment/channel/index.js";
import { getDepartmentList } from "@/api/AttractInvestment/follow/index.js";
import useUserStore from "@/store/modules/user";
const userStr = useUserStore();
const { username, nickname, gszt, deptId, deptName } = userStr;

// 只保留日期部分
function dateOnlyFormatter(row, column, cellValue) {
  if (!cellValue) return "";
  // 支持2023-09-09 12:00:00或2023-09-09T12:00:00Z等
  return String(cellValue).split(" ")[0].split("T")[0];
}
//编辑↓
// 新增编辑弹窗控制变量
const editDialogVisible = ref(false);
const editFormData = reactive({
  id: "",
  tname: "",
  channelId: "",
  channelLevel: "",
  attribution: "",
  category: "",
  isSigned: "",
  channelName: "",
  maintenanceStaff: "",
  contactPerson: "",
  contactInfo: "",
});

// 编辑表单引用
const editFormRef = ref(null);

// 根据ID获取渠道详情
import { getChannelById } from "@/api/AttractInvestment/channel/index.js";

const viewCompanyProfile = (companyId) => {
  if (!companyId) {
    proxy.$modal.msgSuccess("功能未实现，敬请期待");
    return;
  }

  // 查询详情并打开编辑弹窗
  getChannelById(companyId)
    .then((res) => {
      if (res.code === 200 && res.data) {
        // 数据回显
        Object.keys(editFormData).forEach((key) => {
          editFormData[key] = res.data[key] || "";
        });
        editFormData.tname = nickname; // 保持当前用户为提报人员
        editFormData.maintenanceStaff = nickname; // 保持当前用户为维护人员

        editDialogVisible.value = true;
      } else {
        proxy.$modal.msgError(res.msg || "获取详情失败");
      }
    })
    .catch((error) => {
      console.error("获取详情失败:", error);
    });
};

// 编辑提交
import { updateChannel } from "@/api/AttractInvestment/channel/index.js";

function handleEditSubmit() {
  editFormRef.value.validate((valid) => {
    if (valid) {
      updateChannel(editFormData)
        .then((res) => {
          if (res.code === 200) {
            proxy.$modal.msgSuccess("更新成功");
            editDialogVisible.value = false;
            getList(); // 刷新列表
          } else {
            proxy.$modal.msgError(res.msg || "更新失败");
          }
        })
        .catch((error) => {
          console.error("更新渠道失败:", error);
        });
    }
  });
}

// 关闭编辑弹窗
function handleCloseEdit() {
  editDialogVisible.value = false;
  // 重置表单
  editFormRef.value.resetFields();
}
//编辑↑

const loading = ref(false);
const total = ref(0);
const companyList = ref([]);
const activeTab = ref("0");
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  channelName: "",
});

// 字段配置
const fieldConfig = {
  0: [
    // 渠道总表
    { prop: "index", label: "序号" },
    { prop: "channelId", label: "渠道编号" },
    { prop: "channelName", label: "渠道名称" },
    { prop: "attribution", label: "归属" },
    { prop: "channelLevel", label: "渠道级别" },
    { prop: "category", label: "分类" },
    { prop: "maintenanceStaff", label: "维护人员" },
    { prop: "isSigned", label: "是否签约" },
    { prop: "contactPerson", label: "联系人" },
    { prop: "contactInfo", label: "联系方式" },
    { prop: "reportTime", label: "报备时间" },
  ],
  1: [
    // 渠道客户
    { prop: "index", label: "序号" },
    { prop: "channelName", label: "渠道名称" },
    { prop: "relatedCompany", label: "关联企业名称" },
    { prop: "recruiter", label: "招商员" },
    { prop: "project", label: "入驻项目" },
    { prop: "registerType", label: "注册类型" },
    { prop: "finishDate", label: "办结日期" },
    { prop: "enterType", label: "入驻方式" },
    { prop: "rentArea", label: "租赁面积" },
    { prop: "totalTax", label: "累计税收" },
  ],
  2: [
    // 渠道维护
    { prop: "index", label: "序号" },
    { prop: "channelName", label: "渠道名称" },
    { prop: "maintainTime", label: "维护时间" },
    { prop: "maintainContent", label: "维护内容" },
    { prop: "updater", label: "更新人员" },
  ],
  3: [
    // 我的渠道
    { prop: "index", label: "序号" },
    { prop: "channelId", label: "渠道编号" },
    { prop: "channelName", label: "渠道名称" },
    { prop: "channelLevel", label: "渠道级别" },
    { prop: "category", label: "分类" },
    { prop: "maintenanceStaff", label: "维护人员" },
    { prop: "isSigned", label: "是否签约" },
  ],
};

import { useRouter } from "vue-router";
const router = useRouter();

// 根据当前标签页获取对应的API函数
const getApiFunction = () => {
  const apiMap = {
    0: getChannelMasterTableListpage, // 渠道总表
    1: getChannelCustomtpage, // 渠道客户
    2: getChannelMaintainpage, // 渠道维护
    3: getMyChannelpage, // 我的渠道
  };
  return apiMap[activeTab.value] || getChannelMasterTableListpage;
};

// 获取列表数据
function getList() {
  loading.value = true;

  const apiFunction = getApiFunction();

  apiFunction(queryParams)
    .then((res) => {
      console.log("API响应数据:", res);

      // 检查响应码 - 你的系统使用 code: 200 表示成功
      if (res && res.code === 200 && res.data) {
        const pageData = res.data;
        let dataList = [];

        // 获取数据列表
        if (Array.isArray(pageData.records)) {
          dataList = pageData.records;
        }

        console.log("原始数据:", dataList);

        // 处理序号 - 添加到每行数据中
        dataList = dataList.map((item, index) => {
          return {
            ...item,
            index: (queryParams.pageNum - 1) * queryParams.pageSize + index + 1,
          };
        });

        companyList.value = dataList;
        total.value = pageData.total || 0;

        console.log("处理后数据:", companyList.value);
        console.log("数据量:", companyList.value.length);
        console.log("总数:", total.value);
      } else {
        console.log("响应数据格式错误或操作失败:", res);
        companyList.value = [];
        total.value = 0;
        if (res && res.msg) {
          proxy.$modal.msgError(res.msg);
        }
      }
    })
    .catch((error) => {
      console.error("API请求错误:", error);
      companyList.value = [];
      total.value = 0;
    })
    .finally(() => {
      loading.value = false;
    });
}

// 标签页切换处理
function handleTabChange(tab) {
  // 重置查询参数
  resetQueryParams();
  // 重新获取数据
  getList();
}

// 重置查询参数
function resetQueryParams() {
  queryParams.pageNum = 1;
  queryParams.channelName = "";
  // 根据不同的标签页可以设置不同的默认参数
  switch (activeTab.value) {
    case "0": // 渠道总表
      break;
    case "1": // 渠道客户
      break;
    case "2": // 渠道维护
      break;
    case "3": // 我的渠道
      break;
    default:
      break;
  }
}

// 查看企业档案
// const viewCompanyProfile = (companyId) => {
//   if (!companyId) {
//     proxy.$modal.msgSuccess("功能未实现，敬请期待");
//     return;
//   }
//   router.push({
//     path: "/lookCompany",
//     query: { companyId },
//   });
// };

// 搜索处理
function handleQuery() {
  queryParams.pageNum = 1;
  getList();
}

// 重置查询
function resetQuery() {
  resetQueryParams();
  getList();
}

// 弹窗控制
const dialogVisible = ref(false);

// 表单数据
const formData = reactive({
  tname: nickname,
  channelLevel: "",
  attribution: "",
  category: "",
  isSigned: "",
  channelName: "",
  maintenanceStaff: nickname,
  contactPerson: "",
  contactInfo: "",
});

// 验证规则
const rules = {
  channelLevel: [{ required: true, message: "请选择渠道级别", trigger: "change" }],
  category: [{ required: true, message: "请选择渠道分类", trigger: "change" }],
  isSigned: [{ required: true, message: "请选择是否签约", trigger: "change" }],
  channelName: [
    { required: true, message: "请输入渠道名称", trigger: "blur" },
    {
      min: 1,
      max: 20,
      message: "渠道名称长度不能超过20个字符",
      trigger: "blur",
    },
    {
      pattern: /^[\u4e00-\u9fa5a-zA-Z]+$/,
      message: "只能输入汉字和英文",
      trigger: "blur",
    },
  ],
  contactPerson: [
    { required: true, message: "请输入联系人姓名", trigger: "blur" },
    {
      min: 1,
      max: 10,
      message: "联系人姓名长度不能超过10个字符",
      trigger: "blur",
    },
    {
      pattern: /^[\u4e00-\u9fa5a-zA-Z]+$/,
      message: "只能输入汉字和英文",
      trigger: "blur",
    },
  ],
  contactInfo: [
    { required: true, message: "请输入手机号码", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
};

// 表单引用
const formRef = ref(null);

// 新增渠道 - 使用弹窗方式
function handleAddChannel() {
  dialogVisible.value = true;
  //发起查询部门调用
  getDeptList();
}

// 部门列表
const departmentList = ref([]);
// 获取部门列表数据
const getDeptList = async () => {
  console.info("------start-----------");

  loading.value = true;
  try {
    const res = await getDepartmentList();
    console.info("------获取部门列表数据-----------", res.data);
    // 验证响应结构
    if (!res || res.code !== 200) {
      console.warn("获取部门列表：响应格式不正确", res);
      departmentList.value = [];
      return;
    }

    // 处理部门列表数据，确保为数组
    if (Array.isArray(res.data)) {
      departmentList.value = res.data;
    } else if (
      res.data &&
      typeof res.data === "object" &&
      typeof res.data.length === "number"
    ) {
      // 处理类数组对象
      departmentList.value = Array.from(res.data);
    } else {
      console.warn("获取部门列表：数据格式不正确，期望数组类型", res.data);
      departmentList.value = [];
    }
  } catch (error) {
    console.error("获取部门列表失败:", error);
    departmentList.value = [];
  } finally {
    loading.value = false;
  }
};
// 提交表单
function handleSubmit() {
  formRef.value.validate((valid) => {
    if (valid) {
      // 调用 API 创建渠道
      console.log("提交数据:", formData);
      addChannel(formData)
        .then((res) => {
          if (res.code === 200) {
            proxy.$modal.msgSuccess("新增成功");
            dialogVisible.value = false;
            getList(); // 刷新列表
          } else {
            proxy.$modal.msgError(res.msg || "新增失败");
          }
        })
        .catch((error) => {
          console.error("新增渠道失败:", error);
        });
    }
  });
}

// 关闭弹窗
function handleClose() {
  dialogVisible.value = false;
}

onMounted(() => {
  getList();
});

// 在 script 部分添加以下函数
const getChannelLevelTagClass = (level) => {
  switch (level) {
    case "公司级":
      return "custom-tag-primary";
    case "项目部门级":
      return "custom-tag-secondary";
    case "个人级":
      return "custom-tag-tertiary";
    default:
      return "custom-tag-default";
  }
};
const getCategoryTagClass = (level) => {
  switch (level) {
    case "商会协会":
      return "custom-tag-four";
    case "会所律所":
      return "custom-tag-secondary";
    case "中介服务":
      return "custom-tag-one";
    case "合作企业":
      return "custom-tag-two";
    case "财税公司":
      return "custom-tag-three";
    case "政府部门":
      return "custom-tag-primary";
    default:
      return "custom-tag-default";
  }
};
</script>

<style scoped>
.custom-tag-one {
  background-color: #f0fff4 !important;
  border-color: #9ae6b4 !important;
  color: #41999f !important;
}

.custom-tag-two {
  background-color: #ebf8ff !important;
  border-color: #90cdf4 !important;
  color: #5c3772 !important;
}

.custom-tag-three {
  background-color: #fff5f5 !important;
  border-color: #fed7d7 !important;
  color: #406484 !important;
}

.custom-tag-four {
  background-color: #f7fafc !important;
  border-color: #e2e8f0 !important;
  color: #cbaf58 !important;
}

.custom-tag-primary {
  background-color: #fff5f5 !important;
  border-color: #fed7d7 !important;
  color: #c53030 !important;
}

.custom-tag-secondary {
  background-color: #f0fff4 !important;
  border-color: #9ae6b4 !important;
  color: #38a169 !important;
}

.custom-tag-tertiary {
  background-color: #ebf8ff !important;
  border-color: #90cdf4 !important;
  color: #3182ce !important;
}

.custom-tag-default {
  background-color: #f7fafc !important;
  border-color: #e2e8f0 !important;
  color: #4a5568 !important;
}
.record-container {
  padding: 24px 32px 0 32px;
  min-height: 100vh;
}
.filter-card {
  margin-bottom: 12px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  border: 1px solid #f0f0f0;
}
.filter-form {
  padding: 8px 0 0 0;
}
.list-card {
  margin-bottom: 18px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  border: 1px solid #f0f0f0;
}
.el-table {
  border-radius: 8px;
  font-size: 15px;
}
.el-table th {
  color: #333;
  font-weight: 600;
  border-bottom: 1px solid #ebeef5;
}
.el-table td {
  color: #444;
  border-bottom: 1px solid #f0f0f0;
}
.el-button[type="primary"] {
  background: linear-gradient(90deg, #4f8cff 0%, #38c8fa 100%);
  border: none;
  color: #fff;
  border-radius: 6px;
  font-weight: 500;
  box-shadow: 0 2px 8px rgba(32, 159, 240, 0.08);
  transition: background 0.2s;
}
.el-button[type="primary"]:hover {
  background: linear-gradient(90deg, #2563eb 0%, #38c8fa 100%);
}
.dialog-footer {
  text-align: right;
}
</style>
